App.factory('API', [ '$http', '$q', 'ngDialog', function ($http, $q, ngDialog) {
	
	return {
		
		call: function(url, params){
			
			$('#loadingModal').modal({
				backdrop: 'static',
				keyboard: false
			});
			
			var defered = $q.defer();
			
			$http({
				method: 'post',
				url: url,
				data: params
			}).success(function(response, status, headers, config){
				
				$('#loadingModal').modal('hide');
				defered.resolve(response);
			}).error(function(response, status, headers, config){
				
				$('#loadingModal').modal('hide');
				if(status != 401 && status != 404 && status != 500 && status != 518 ){
					
					ngDialog.open({
				        template: '<h4>呼叫API:'+ url +'发生错误。</h4>',
				        plain: true,
				        closeByDocument: false,
				        closeByEscape: false
				    });
				}
			});
			
			return defered.promise;
		},
		
		download: function(url,params) {
			
			$http({
				method: 'post',
				url: url,
				data: params,
				reponseType: 'arraybuffer'
			}).success(function(response, status, headers, config){
				
				var file = new File([response], params, {type: "text/plain;charset=utf-8"});
				
				saveAs(file);
			}).error(function(response, status, headers, config){
				
				if(status != 401 && status != 404 && status != 500 && status != 518 ){
					
					ngDialog.open({
				        template: '<h4>呼叫API:'+ url +'发生错误。</h4>',
				        plain: true,
				        closeByDocument: false,
				        closeByEscape: false
				    });
				}
			});
		}
	};
}]);